<?php
namespace app\console\controller;

use app\console\model\MemberOrderAttached as MemberOrderAttachedModel;
use app\client\model\MemberOrder as MemberOrderModel;
use app\client\model\MemberRefund as MemberRefundModel;
use app\client\model\Express as ExpressModel;
use think\Db;
use think\Url;
use think\Request;
use think\Controller;
use think\Session;
use app\common\excel\Export;


class MemberOrder extends Controller
{
    /*
     * 订单列表
     */
    public function index()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
//        $condition['shop_id'] = ['eq', Session::get('shop_id')];
        $condition['status'] = ['notin','6,7,9,10,11'];



        if (isset($inquire['status']) && $inquire['status'] <> '-1') $condition['status'] = ['eq', $inquire['status']];
        if (isset($inquire['title']) && !empty($inquire['title'])) $condition['member.username'] = ['eq', $inquire['title']];

        if (!empty($inquire['interval_timer'])) {

            $interval_timer = explode(' / ', $inquire['interval_timer']);
            $condition['create_time'] = ['between time', [strtotime($interval_timer[0]), strtotime($interval_timer[1])]];

        }

        // 读取
        $data = Db::view('member_order', 'use_balance,use_integral,pay_price,id,shop_order_number,shop_id,member_id,create_time,price,way,freight,status')
            ->view('shop', 'member_id,title', 'shop.member_id = member_order.shop_id','left')
            ->view('member', 'id as user_id,username', 'member.id = member_order.member_id','left')
            ->where($condition)
            //->fetchSql(true)
            ->order(['create_time' => 'desc'])
            ->paginate(10, false, ['query' => $inquire]);
       //halt($data);
        $total_order = Db::view('member_order', 'id,shop_order_number,shop_id,member_id,create_time,price,way,status')
            ->view('shop', 'member_id,title', 'shop.member_id = member_order.shop_id','left')
            ->view('member', 'id as user_id,username', 'member.id = member_order.member_id','left')
            ->where($condition)->count();

        // 订单总价
        $total_account = Db::view('member_order', 'id,shop_order_number,shop_id,member_id,create_time,price,way,status')
            ->view('shop', 'member_id,title', 'shop.member_id = member_order.shop_id','left')
            ->view('member', 'id as user_id,username', 'member.id = member_order.member_id','left')
            ->where($condition)->sum('price');



        return $this->fetch('index', [
            'mate_title' => '订单列表',
            'data'       => $data,
            'total_order' => $total_order,
            'total_account' => $total_account,
        ]);
    }

    /*
     * 订单查看
     */
    public function examine($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();
            // 提交数据
            $dispose = (new MemberOrderModel())->allowField(true)->save($data, ['id' => $id]);

            if ($dispose !== false) {
                if($data['status'] == 2){
                    $goods_sum = db('member_order_attached')->where('shop_order_number',$data['order_number'])->sum('number');
                    $message_id = db('member_message')->insertGetId(['type' => 2,'member_id' => $data['member_id'],'title' => $data['order_number'],'content' => '您的订单已发货,共'.$goods_sum.'商品','create_time' => date('Y-m-d H:i:s',time())]);
                    db('mem_mess')->insert(['member_id' => $data['member_id'],'message_id' => $message_id,'create_time' => time(),'click' => 0]);
                }
                win('操作成功', Url::build('MemberOrder/index'));
            }

            fail('操作失败');

        }

        $item = Db::view('member_order', '*')
            ->view('shop', 'member_id as user_id,title', 'shop.member_id = member_order.shop_id','left')
            ->view('member', 'id as user_id,username', 'member.id = shop.member_id','left')
            ->where(['member_order.id' => $id])
            ->order(['create_time' => 'desc'])
            ->find();
        $item['buyers'] = Db::name('member')->where('id',$item['member_id'])->value('username');


        $goods_list = MemberOrderAttachedModel::where(['order_id' => $id])->select();

        $express_list = ExpressModel::all();

        $refund_find = MemberRefundModel::where(['order_number' => $item['shop_order_number']])->find();


        return $this->fetch('', [
            "mate_title"   => '订单详情',
            'item'         => $item,
            'goods_list'   => $goods_list,
            'express_list' => $express_list,
            'refund_find'  => $refund_find,

        ]);
    }


    /**
     * 表格数据提供
     * @param $start_time
     * @param $end_time
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function excelDownload($start_time, $end_time,$status)
    {

        //$condition['status'] = $status;
        if (isset($status) && $status <> '-1') $condition['status'] = ['eq', $status];
        $condition['create_time'] = ['between time', [$start_time, $end_time]];

        $data = Db::view('member_order', 'use_balance,use_integral,pay_price,id,shop_order_number,shop_id,member_id,create_time,price,way,price,coupon_price,red_packet_price,status,address_name,address_area,pay_time,address_phone,address_site')
            ->view('shop', 'member_id,title', 'shop.member_id = member_order.shop_id','left')
            ->view('member_order_attached','shop_order_number,title as g_title,number,price as g_price','member_order.shop_order_number = member_order_attached.shop_order_number','left')
            ->view('member', 'id as user_id,username', 'member.id = member_order.member_id','left')
            ->where($condition)
            ->order(['create_time' => 'desc'])->fetchSql(false)->select()->toArray();
        if($data){
            foreach ($data as $k => &$v){
                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }

        return $data;
    }



    /**
     * 导出表格
     */
    public function export()
    {
        // 获取参数
        $inquire = Request::instance()->param();
        $interval_timer = explode(' / ', $inquire['interval_timer']);
        $name = $interval_timer[0] . '至' . $interval_timer[1] . "订单状况";
        $start_time = strtotime($interval_timer[0]);
        $end_time = strtotime($interval_timer[1]);

        //返回的合并数据
        $return = self::excelDownload($start_time, $end_time,$inquire['status']);

        //导出excel
        (new Export())->export($name, $return);
    }

}
